/*
 * www.acooly.cn Inc.
 * Copyright (c) 2017 All Rights Reserved
 */

/*
 * 修订记录:
 * zhangpu@acooly.cn 2017-09-27 15:15 创建
 */
package com.acooly.module.openapi.client.api.util;

import com.acooly.core.utils.Money;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.lang.reflect.Type;

/**
 * Json Mapping工具
 *
 * copy from openapi-framework
 *
 * @author zhangpu 2017-09-27 15:15
 */
public class Jsons {
    private static ParserConfig parserConfig = new ParserConfig();

    static {
        parserConfig.putDeserializer(Money.class, MoneyDeserializer.instance);
    }

    public static <T> T parse(String source, Type clazz) {
        ParserConfig.getGlobalInstance().putDeserializer(Money.class, MoneyDeserializer.instance);
        int featureValues = (~Feature.SortFeidFastMatch.getMask()) & JSON.DEFAULT_PARSER_FEATURE;
        return JSON.parseObject(source, clazz, parserConfig, featureValues, new Feature[0]);
    }


    public static String toJson(Object object) {
        if (object == null) {
            return "{}";
        }
        SerializeWriter out = new SerializeWriter();
        try {
            JSONSerializer serializer = getJsonSerializer(out);
            serializer.write(object);
            return out.toString();
        } finally {
            out.close();
        }
    }


    protected static JSONSerializer getJsonSerializer(SerializeWriter out) {
        SerializeConfig serializeConfig = new SerializeConfig();
        serializeConfig.put(Money.class, MoneySerializer.INSTANCE);
        JSONSerializer serializer = new JSONSerializer(out, serializeConfig);
        serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
        serializer.setDateFormat("yyyyMMddHHmmss");
        serializer.config(SerializerFeature.QuoteFieldNames, true);
        serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);

        return serializer;
    }


}
